package com.atguigu.service.impl;

import com.atguigu.entity.Mail;
import com.atguigu.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * MailServiceImpl
 *
 * @author yangchao
 * @version 开发阶段
 * @description TODO
 * @date 2022/3/14 11:40
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {
    @Autowired
    private JavaMailSender mailSender;
    @Value("${mail.from}")
    private String mailFrom;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void sendSimpleMail(String mailTo) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailFrom);
        message.setTo(mailTo);
        message.setSubject("电商网站注册验证");
        String content = templateRegister(mailTo);
        message.setText(content);
        mailSender.send(message);
        log.info("邮件已经发送:"+content);
    }

    @Override
    public Integer verificationCode(Mail mail) {
        Integer code = (Integer) redisTemplate.opsForValue().get(mail.getMail());
        if(code.equals(mail.getCode())){
            return 2;
        }
        return 1;
    }


    private String templateRegister(String mailTo) {
        String str = null;
        Integer code = null;
        String key = mailTo;
        code = (Integer) redisTemplate.opsForValue().get(key);
        if (code == null) {
            synchronized (MailServiceImpl.class) {
                code = (Integer) redisTemplate.opsForValue().get(key);
                if (code == null) {
                    Random random = new Random();
                    code = random.nextInt(999999);
                    if (code < 100000) {
                        code = code + 10000;
                    }
                    redisTemplate.opsForValue().setIfAbsent(key, code, 60 * 5L, TimeUnit.SECONDS);
                }
            }
        }
        str = "【电商网站】您正在注册电商网站短信平台，您的验证码是【" + code + "】,5分钟内有效。验证码是系统根据一定规则自动生成，无需人工干预。";
        return str;
    }
}




